package mvc.xml;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

/**
 * xml配置对象的解析工具类
 * 
 * @author jiangchao
 *
 */
public class XmlBeanParse {
	private XmlBeanParse() {

	}

	public static Map<String, XmlBean> parse(String filePath) throws JDOMException, IOException {
		Map<String, XmlBean> result = new HashMap<String, XmlBean>();
		SAXBuilder builder = new SAXBuilder();
		Document document = builder.build(new File(filePath));
		Element root = document.getRootElement();

		Element actionMappings = root.getChild("action-mappings");
		List<Element> actions = actionMappings.getChildren();
		for (Element action : actions) {
			XmlBean xmlBean = new XmlBean();

			Map<String, String> map = new HashMap<String, String>();
			String name = action.getAttributeValue("name");
			xmlBean.setName(name);
			String type = action.getAttributeValue("type");
			xmlBean.setActionType(type);
			String path = action.getAttributeValue("path");
			xmlBean.setActionPath(path);

			Element formBeans = root.getChild("formBeans");
			List<Element> formBeanList = formBeans.getChildren();
			for (Element formBean : formBeanList) {
				if (name.equals(formBean.getAttributeValue("name"))) {
					String formClassPath = formBean.getAttributeValue("class");
					xmlBean.setFormClass(formClassPath);
					break;
				}
			}
			List<Element> forwards = action.getChildren();
			for (Element forward : forwards) {
				String forwardName = forward.getAttributeValue("name");
				String forwardUrl = forward.getAttributeValue("url");
				map.put(forwardName, forwardUrl);
			}
			xmlBean.setForward(map);
			result.put(path, xmlBean);
		}

		return result;
	}

}
